/**
 * Copyright (C)  2011  chen wei hua.
 * Permission is granted to copy, distribute and/or modify this document
 * under the terms of the GNU Free Documentation License, Version 2.0
 * or any later version published by the Free Software Foundation;
 * with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.
 * A copy of the license is included in the section entitled "GNU Free Documentation License".
 */
package com.javaeye.plan.dao;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.criterion.Subqueries;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.javaeye.common.dto.DTO;
import com.javaeye.plan.dto.InStoreVoucher;
import com.javaeye.plan.dto.InStoreVoucherDetail;
import com.javaeye.plan.web.VoucherCondition;
import com.javaeye.common.web.PageInfo;

public class InStoreVoucherDAOHibernate extends HibernateDaoSupport implements InStoreVoucherDAO {
	
	@SuppressWarnings("unchecked")
	public int getMaxInStoreVoucherId(String voucherId) {
		final String queryString = "select max(v.id) from InStoreVoucher v where v.id like ?";
		List result = getHibernateTemplate().find(queryString, voucherId + "%");
		if (result.get(0) == null) {
			return 0;
		}
		String maxId = result.get(0).toString();
		maxId = maxId.replace(voucherId, "");
		return Integer.parseInt(maxId);
	}
	
	@Override
	public void saveInStoreVoucher(final InStoreVoucher voucher) {
		HibernateCallback action = new HibernateCallback() {
			@Override
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				List<Integer> removeDetailIds = voucher.getRemoveDetailIdList();
				for (int id : removeDetailIds) {
					InStoreVoucherDetail detail = 
						(InStoreVoucherDetail)session.load(InStoreVoucherDetail.class, id);
					session.delete(detail);
				}
				session.saveOrUpdate(voucher);
				return null;
			}
		};
		getHibernateTemplate().execute(action);
	}
	
	public InStoreVoucher getInStoreVoucher(String voucherId) {
		InStoreVoucher voucher = (InStoreVoucher)getHibernateTemplate().get(InStoreVoucher.class, voucherId);
		//由于使用延迟加载，这里需要强制取出关联集合
		Hibernate.initialize(voucher.getVoucherDetails());
		return voucher;
	}
	
	public void removeInStoreVoucher(String voucherId) {
		InStoreVoucher v = (InStoreVoucher)getHibernateTemplate().load(InStoreVoucher.class, voucherId);
		getHibernateTemplate().delete(v);
	}
	
	@SuppressWarnings("unchecked")
	public List getPageData(final DTO contidions, final PageInfo pageInfo) {
		HibernateCallback action = new HibernateCallback() {
			@Override
			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				
				int pageIndex = pageInfo.getPageIndex();
				int pageSize = pageInfo.getPageSize();
				VoucherCondition contidion = (VoucherCondition)contidions;
				//Criteria crit = session.createCriteria(InStoreVoucher.class);
				DetachedCriteria crit = DetachedCriteria.forClass(InStoreVoucher.class);
				Date beginDate = contidion.getBeginDate();
				Date endDate = contidion.getEndDate();
				if (beginDate != null && endDate != null) {
					crit.add(Restrictions.between("createDate", beginDate, endDate));
				}
				
				String voucherNo = contidion.getVoucherNo().trim();
				if (!"".equals(voucherNo)) {
					crit.add(Restrictions.eq("id", voucherNo));
				}
				
				String checkNo = contidion.getCheckNo().trim();
				if (!"".equals(checkNo)) {
					crit.add(Restrictions.eq("checkNo", checkNo));
				}
				
				String batchNo = contidion.getBatchNo().trim();
				int skuId = contidion.getSkuId();
				if (!"".equals(batchNo)) {
					//这里的batchNo会造成关联表重复记录产生
					DetachedCriteria detailCrit = crit.createAlias("voucherDetails", "d")
						.add(Restrictions.like("d.batchNo", "%" + batchNo + "%"));
					if (skuId != -1) {
						detailCrit.add(Restrictions.eq("d.productId", skuId));
					}
				} else if (skuId != -1) {
					crit.createAlias("voucherDetails", "d")
						.add(Restrictions.eq("d.productId", skuId));
				}
				
				int status = contidion.getStatus();
				if (status != -1) {
					crit.add(Restrictions.eq("status", status));
				}
				crit.setProjection(Projections.distinct(Projections.id()));
				
				//这里使用子查询，去除关联重复记录
				Criteria resultCrit = session.createCriteria(InStoreVoucher.class);
				resultCrit.add(Subqueries.propertyIn("id", crit));
				
				//按照创建日期倒序排序
				resultCrit.addOrder(Order.desc("createDate"));
				
				resultCrit.setProjection(Projections.rowCount());
				Integer rowNumber = (Integer)resultCrit.uniqueResult();
				pageInfo.setCount(rowNumber);
				
				resultCrit.setProjection(null);//取得了总数后,为了能够再次取得对象列表
				resultCrit.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);//当hibernate采用关联的时候不使用这个返回的是个对象数组，加上这个返回的是当前列表的对象。
				resultCrit.setFirstResult(pageIndex * pageSize);
				resultCrit.setMaxResults(pageSize);
				return resultCrit.list();
			}
		};
		return getHibernateTemplate().executeFind(action);
	}

}
